// 认证相关 API
import request from '@/utils/request';
import { UserInfo } from '@/types/user';

// 登录表单接口
export interface LoginForm {
  mobile: string;
  code: string;
}

// 登录响应接口
export interface LoginResponse {
  token: string;
  refreshToken: string;
  user: UserInfo;
}

// 微信登录响应
export interface WechatLoginResponse {
  isFirstLogin: boolean;
  token?: string;
  user?: UserInfo;
  tempUserInfo?: {
    openid: string;
    nickname: string;
    avatar: string;
  };
}

// 短信登录表单
export interface SmsLoginForm {
  mobile: string;
  code: string;
}

// 短信登录响应
export interface SmsLoginResponse {
  accessToken: string;
  source: string;
  userId: string;
  userRoleType: string | null;
  teamId: string | null;
  identityAuthenticationId: string | null;
  shippingAddressId: string | null;
  name: string;
  phoneNumber: string;
  identityType: string;
  area: string;
  researchDirection: string;
  affiliatedInstitution: string;
  unit: string;
  position: string;
  status: number;
}

// 绑定手机号表单
export interface BindPhoneForm {
  phone: string;
  code: string;
  openid: string;
}

// 绑定微信表单
export interface BindWechatForm {
  userId: string;
  openid: string;
}

export const authApi = {
  // 扫描登录
  login: (data: LoginForm): Promise<LoginResponse> =>
    request.post('/admin/auth/valid', data),

  
  // 微信登录
  wechatLogin: (openid: string): Promise<WechatLoginResponse> =>
    request.post('/admin/auth/wechat-login', { openid }),
  // 发送短信验证码
  sendSmsCode: (mobile: string): Promise<void> =>
    request.post('/admin/auth/login', { mobile }),

  // 短信登录
  smsLogin: (data: SmsLoginForm): Promise<SmsLoginResponse> =>
    request.post('/admin/auth/valid', data),

  // 绑定手机号
  bindPhone: (data: BindPhoneForm): Promise<LoginResponse> =>
    request.post('/auth/bind-phone', data),

  // 绑定微信
  bindWechat: (data: BindWechatForm): Promise<LoginResponse> =>
    request.post('/auth/bind-wechat', data),

  // 登出
  logout: (): Promise<void> =>
    request.post('/auth/logout'),

  // 刷新 token
  refreshToken: (refreshToken: string): Promise<{ token: string }> =>
    request.post('/auth/refresh', { refreshToken }),

  // 获取当前用户信息
  getCurrentUser: (): Promise<UserInfo> =>
    request.get('/auth/current'),

  // 修改密码
  changePassword: (data: { oldPassword: string; newPassword: string }): Promise<void> =>
    request.post('/auth/change-password', data),

  // 获取微信登录二维码
  getWechatQrCode: (): Promise<{ qrCodeUrl: string; scene: string }> =>
    request.get('/auth/wechat-qr-code'),

  // 检查微信扫码状态
  checkWechatScanStatus: (scene: string): Promise<{ status: 'waiting' | 'scanned' | 'confirmed'; userInfo?: UserInfo }> =>
    request.get(`/auth/wechat-scan-status/${scene}`),
}; 